<template>
  <div class="main-tab h-max">
    <div v-if="executed">执行成功</div>
    <div v-if="!$store.getters['examine/getIsExamine']" class="layout mb-10">
      <el-button
        type="warning"
        plain
        :loading="isDeploying"
        :disabled="isDeploying"
        size="small"
        @click="deploy"
      >
        部署代码
      </el-button>
    </div>
    <div class="editor ">
      <div class="left h-max">
        <div class="module h-max">
          <div class="module-title dis-flex space-between">
            <i />
            <label> 目录 </label>
            <icon-more
              trigger="click"
              :dropdown-items="dropdownRootItems"
              :click-functions="clickFunctions"
            />
          </div>

          <div class="module-content">
            <function-folder-tree ref="functionTree" />
          </div>
        </div>
      </div>
      <div class="right h-max">
        <div class="module h-max">
          <div class="module-title dis-flex space-between">
            <i />
            <label>编辑器</label>
            <i />
          </div>
          <div class="module-content">
            <function-editor-tabs />
          </div>
        </div>
      </div>
    </div>
    <file-upload-dialog ref="fileUploadDialog" />
  </div>
</template>
<script>
import FunctionFolderTree from '../plugins/FunctionFolderTree.vue';
import IconMore from '@/components/icon/IconMore.vue';
import FunctionEditorTabs from '../plugins/FunctionEditorTabs.vue';
import FileUploadDialog from '@/views/functions/components/FileUploadDialog';
import { getFunctions } from '@/api/userProjectLibrary';
import { mapActions, mapState } from 'vuex';

export default {
  name: 'MainTab',
  components: {
    FunctionEditorTabs,
    IconMore,
    FunctionFolderTree,
    FileUploadDialog
  },
  props: {
    timeOut: {
      type: String,
      required: true
    },
    memorySize: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      dropdownRootItems: [
        { type: 'buildFolder', label: '创建文件夹' },
        { type: 'buildFile', label: '创建脚本' },
        { type: 'upload', label: '上传' }
      ],

      treeData: undefined,
      isDeploying: false,
      executed: false
    };
  },
  computed: {
    ...mapState('functions', ['serviceName', 'functionName', 'usePublicLayers'])
  },
  mounted() {
    document.addEventListener('keydown', this.saveEvent);
    console.log(this.serviceName);
    getFunctions({ libraryName: this.serviceName }).then((res) => { // 获取当前编辑的函数
      const data = res.functions.find((element) => element.functionName === this.functionName);
      try {
        this.treeData = JSON.parse(data.filePathJson);
      } catch {
        this.treeData = [];
      }
      this.$refs.functionTree.setData(this.treeData);
    });
  },
  methods: {
    ...mapActions('functions', ['updateAliFunction']),
    clickFunctions(type) {
      switch (type) {
        case 'buildFolder':
        case 'buildFile':
          this.$store.commit('functions/append', {
            nodeType: 'father',
            type
          });
          break;
        case 'upload':
          this.$store.commit('functions/setUploadNode', null);
          this.$refs.fileUploadDialog.show();
          break;
        default:
          console.log(type);
      }
    },
    saveEvent(e) {
      // js监听键盘ctrl+s快捷键保存
      if (
        e.keyCode === 83 &&
          (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)
      ) {
        e.preventDefault();
        const store = this.$store.state.functions;
        if (store.editorFiles.length) {
          const file = store.editorFiles.find(
            (item) => item.id === store.editorFilesId
          );
          if (store.isUploadFile[file.id]) {
            this.$message.error('文件正在部署中...');
            return;
          }
          if (file && file.display === 'file' && file.editText !== file.editContent) {
            this.$store.dispatch('functions/buildFiles', {
              type: 'update',
              id: file.id,
              text: file.editContent,
              path: file.path
            });
          }
        }
      }
    },
    async deploy() {
      const functions = this.$store.state.functions;
      await Promise.all(functions.editorFiles.map(async(file) => {
        if (file && file.display === 'file' && file.editText !== file.editContent) {
          if (functions.isUploadFile[file.id]) {
            this.$message.warning('文件正在部署中...');
            return;
          }
          try {
            await this.$store.dispatch('functions/buildFiles', {
              type: 'update',
              id: file.id,
              text: file.editContent,
              path: file.path
            });
          } catch (err) {
            console.error(err);
          }
        }
      }));
      this.isDeploying = true;
      this.$message({
        type: 'info',
        message: '正在部署'
      });
      // console.log(this.timeOut, this.memorySize);
      this.updateAliFunction({
        usePublicLayers: this.usePublicLayers,
        functionOption: {
          timeOut: this.timeOut,
          memorySize: this.memorySize
        }
      }).then(() => {
        this.$message({
          type: 'success',
          message: '部署成功！'
        });
      }).catch((err) => {
        console.error(err);
      }).finally(() => {
        this.isDeploying = false;
      });
    }
  }
};
</script>
<style lang="scss">
.main-tab {
  display: flex;
  flex-direction: column;

  .editor {
    height: 100%;
    width: 100%;
    flex: 1;
    display: flex;
    border: 1px solid #d5d5d5;

    .left {
      border: 1px solid #d5d5d5;
      width: 20%;
    }
    .right {
      display: flex;
      flex-direction: column;
      width: 80%;
    }

  }

  .button-wrapper {
    height: 32px;
  }

}
</style>
<style scoped>
button:disabled {
  cursor: not-allowed;
}

</style>
